﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using System;
using System.Linq;
using IOA.MES.Common;
using System.Collections.Generic;

namespace IOA.MES.Business
{
    /// <summary>
    /// 标签设置（错误代码：120001）
    /// </summary>
    public class LabelMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public void Edit(VWorkorderLable model)
        {
            var entity = string.IsNullOrWhiteSpace(model.WorkOrderNo) ? mesDb.WorkOrderLables.FirstOrDefault(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.Valid)
                : mesDb.WorkOrderLables.FirstOrDefault(_ => _.OrderNo == "" && _.WorkOrderNo == model.WorkOrderNo && _.Valid);
            if (entity == null)
            {
                model.CreateTime = DateTime.Now;
                if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
                {
                    model.OrderNo = string.Empty;
                }
                entity = Mapper.Map<WorkOrderLable>(model);
                mesDb.WorkOrderLables.Add(entity);
            }
            else
            {
                mesDb.WorkOrderLables.Attach(entity);
                entity.TemplateId = model.TemplateId;
                entity.SerialNum = model.SerialNum;
                entity.BorderBarCode = model.BorderBarCode;
                entity.Nameplate = model.Nameplate;
                entity.CurrentTag = model.CurrentTag;
                entity.EnergyTag = model.EnergyTag;
                entity.Mark = model.Mark;
                entity.PallNumTag = model.PallNumTag;
                entity.FrChart = model.FrChart;
                entity.OBAData = model.OBAData;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 获取工单标签
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <returns>工单标签</returns>
        public VWorkorderLable GetWorkOrderLabel(string orderNo, string workOrderNo)
        {
            if (string.IsNullOrWhiteSpace(workOrderNo))
            {
                var entity = mesDb.WorkOrderLables.FirstOrDefault(_ => _.OrderNo == orderNo && _.WorkOrderNo == "" && _.Valid);
                return Mapper.Map<VWorkorderLable>(entity);
            }
            else
            {
                var entity = mesDb.WorkOrderLables.FirstOrDefault(_ => _.OrderNo == "" && _.WorkOrderNo == workOrderNo && _.Valid);
                if (entity != null)
                {
                    return Mapper.Map<VWorkorderLable>(entity);
                }
                var workOrder = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == workOrderNo && _.Valid);
                if (workOrderNo == null)
                {
                    throw new MultiLanBizException(102022);//工单不存在)
                }
                entity = mesDb.WorkOrderLables.FirstOrDefault(_ => _.OrderNo == workOrder.OrderNo && _.WorkOrderNo == "" && _.Valid);
                return Mapper.Map<VWorkorderLable>(entity);
            }
        }

        /// <summary>
        /// 根据组件条码获取标签配置
        /// </summary>
        /// <param name="barCode">组件条码</param>
        /// <returns>标签配置</returns>
        public VWorkorderLable GetLabelByCode(string barCode)
        {
            var component = mesDb.Components.AsNoTracking().FirstOrDefault(_ => _.BarCode == barCode && _.Valid);
            if (component == null)
            {
                throw new MultiLanBizException(120001);//条码不存在;
            }
            var label = GetWorkOrderLabel("", component.WorkOrderNo);
            return label;
        }

        /// <summary>
        /// 获取包装标签
        /// </summary>
        /// <param name="packNo">包装条码</param>
        /// <returns>标签配置</returns>
        public VWorkorderLable GetLabelByPack(string packNo)
        {
            var pack = mesDb.Packs.FirstOrDefault(_ => _.PackNo == packNo && _.PackStatus == DataAccess.Enum.PackStatus.Normal && _.Valid);
            if (pack == null)
            {
                throw new MultiLanBizException(120001);//条码不存在;
            }
            var label = GetWorkOrderLabel(pack.OrderNo, pack.WorkOrderNo);
            return label;
        }

        /// <summary>
        /// 查询模板列表
        /// </summary>
        /// <param name="page">页面索引</param>
        /// <param name="limit">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="name">模板名称</param>
        /// <returns>模板列表</returns>
        public List<VLabelTemplate> QueryTemplates(int page, int limit, out int total, string name)
        {
            var query = mesDb.LabelTemplates.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.Where(_ => _.TemplateName.Contains(name));
            }
            total = query.Count();

            query = query.OrderByDescending(_ => _.PkId);
            var entities = limit <= 0 ? query.ToList() : query.Skip((page - 1) * limit).Take(limit).ToList();

            return Mapper.Map<List<VLabelTemplate>>(entities);
        }

        /// <summary>
        /// 获取模板对象
        /// </summary>
        /// <param name="templateId">模板ID</param>
        /// <returns>模板对象</returns>
        public VLabelTemplate GetTemplate(int templateId)
        {
            var entity = mesDb.LabelTemplates.AsNoTracking().FirstOrDefault(_ => _.PkId == templateId && _.Valid);
            return Mapper.Map<VLabelTemplate>(entity);
        }

        /// <summary>
        /// 保存模板对象
        /// </summary>
        /// <param name="model">模板对象</param>
        public void SaveTemplate(VLabelTemplate model)
        {
            if (model.PkId <= 0)
            {
                var exist = mesDb.LabelTemplates.AsNoTracking().FirstOrDefault(_ => _.TemplateName == model.TemplateName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(120002);//模板名称已存在，请更换其他名称
                }
                model.CreateTime = DateTime.Now;
                var entity = Mapper.Map<LabelTemplate>(model);
                mesDb.LabelTemplates.Add(entity);
                mesDb.SaveChanges();
            }
            else
            {
                var exist = mesDb.LabelTemplates.AsNoTracking().FirstOrDefault(_ => _.PkId != model.PkId && _.TemplateName == model.TemplateName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(120002);//模板名称已存在，请更换其他名称
                }
                var entity = mesDb.LabelTemplates.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(120003);//模板不存在或已被删除
                }
                mesDb.LabelTemplates.Attach(entity);
                entity.SerialNum = model.SerialNum;
                entity.BorderBarCode = model.BorderBarCode;
                entity.Nameplate = model.Nameplate;
                entity.CurrentTag = model.CurrentTag;
                entity.EnergyTag = model.EnergyTag;
                entity.Mark = model.Mark;
                entity.PallNumTag = model.PallNumTag;
                entity.FrChart = model.FrChart;
                entity.OBAData = model.OBAData;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();
            }
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        /// <param name="model">模板对象</param>
        public void DeleteTemplate(VLabelTemplate model)
        {
            var entity = mesDb.LabelTemplates.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity != null)
            {
                mesDb.LabelTemplates.Attach(entity);
                entity.Valid = false;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();
            }
        }
    }
}
